<template>
  <div class="agreementNew" id="agreementNew">
    <div class="select-wrap" id="queryNewBox">
      <el-form ref="agreementForm" :model="queryForm" :inline="true" label-width="120px">
        <div class="formBox">
          <el-form-item label="协议类型" prop="agreementType">
            <el-select v-model="queryForm.agreementType" placeholder="请选择" @change="agreementTypeChange">
              <el-option label="招投标按趟" value="2"></el-option>
            </el-select>
          </el-form-item>
          <!-- <span class="formTips" v-if="queryForm.agreementType">协议所属区：001/总部</span> -->
        </div>
        <div class="formBox">
          <el-form-item label="计价方式" prop="priceType">
            <el-select v-model="queryForm.priceType" placeholder="请选择">
              <el-option label="元/趟" value="2"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="formBox">
          <el-form-item label="公司名称" prop="companyName">
            <el-select v-model="queryForm.companyName" placeholder="请选择" @change="selectCompany" clearable
              @clear="clearCompany">
              <el-option v-for="item in options" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <span class="formTips"
            v-if="companyItem.blRegisterNumber">统一信用代码：<span>{{companyItem.blRegisterNumber}}</span></span>
          <span class="formTips"
            v-if="companyItem.moreBusinessContactor">联系人：<span>{{companyItem.moreBusinessContactor}}</span></span>
          <span class="formTips"
            v-if="companyItem.moreContactorPhone">联系电话：<span>{{companyItem.moreContactorPhone}}</span></span>
        </div>
        <div class="formBox">
          <el-form-item label="承运商类型" prop="supplierType">
            <el-select v-model="queryForm.supplierType" placeholder="请选择">
              <el-option label="企业" value="B"></el-option>
              <el-option label="个人" value="C"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="formBox" v-show="queryForm.supplierType == 'B'">
          <el-form-item label="承运商名称" prop="supplierUserName">
            <el-select v-model="queryForm.supplierUserName" filterable remote reserve-keyword placeholder="请输入关键词"
              :remote-method="remoteSupplier" :loading="loading1" @change="selectSupplier" clearable
              @clear="clearSupplier">
              <el-option v-for="item in options1" :key="item.value" :label="item.blName" :value="item.username">
              </el-option>
            </el-select>
          </el-form-item>
          <span class="formTips"
            v-if="supplierItem.blRegisterNumber">统一信用代码：<span>{{supplierItem.blRegisterNumber}}</span></span>
          <span class="formTips"
            v-if="supplierItem.moreBusinessContactor">联系人：<span>{{supplierItem.moreBusinessContactor}}</span></span>
          <span class="formTips"
            v-if="supplierItem.moreContactorPhone">联系电话：<span>{{supplierItem.moreContactorPhone}}</span></span>
        </div>
        <div class="formBox" v-show="queryForm.supplierType == 'C'">
          <!-- <el-form-item label="司机手机号" prop="driverPhone">
            <el-select
              v-model="queryForm.driverPhone"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteDriver"
              :loading="loading2"
              @change="selectDriver"
              clearable
              @clear="clearDriver"
            >
              <el-option
                v-for="item in options2"
                :key="item.value"
                :label="item.blName"
                :value="item.username"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="司机手机号" prop="driverPhone">
            <el-popover ref="deptPop" placement="bottom" width="220" trigger="focus" @after-leave="afterLeave"
              :loading="loading2">
              <div class="userItem" v-for="item in options2" :key="item.userId" :value="item.userId"
                @click="chooseUserName(item)">{{item.blName}}/{{item.moreContactorPhone}}</div>
              <el-pagination small layout="prev, pager, next" :pager-count="5" :total="totalUser" :page-size="5"
                @current-change="userPageChange" :current-page="currentUserPage">
              </el-pagination>
              <el-input slot="reference" placeholder="输入用户姓名/手机号查询" clearable v-model.trim="queryForm.driverPhone"
                @clear="totalUser;currentUserPage=1;driverItem={}" @input="queryUserInfoByPage()"></el-input>
            </el-popover>
          </el-form-item>
          <span class="formTips"
            v-if="driverItem.moreBusinessContactor">司机姓名：<span>{{driverItem.moreBusinessContactor}}</span></span>
          <span class="formTips"
            v-if="driverItem.blRegisterNumber">身份证号：<span>{{driverItem.blRegisterNumber}}</span></span>
        </div>
        <div class="formBox dateBox">
          <el-form-item label="协议有效期" prop="dateValue">
            <el-date-picker v-model="queryForm.dateValue" type="datetimerange" range-separator="至"
              start-placeholder="协议生效时间" end-placeholder="协议失效时间" clearable readonly>
            </el-date-picker>
            <span class="formTips">选择线路后自动生成协议有效期</span>
          </el-form-item>
        </div>
        <div class="formBox">
          <el-form-item label="协议类别" prop="agreementCategory">
            <el-select v-model="queryForm.agreementCategory" placeholder="请选择">
              <el-option v-for="item in typeNameList" :key="item.typeCode" :label="item.typeName"
                :value="item.typeCode"></el-option>
            </el-select>
          </el-form-item>
          <el-popover placement="top" width="1000" trigger="click">
            <div v-html="agreementTxt" id="agreementPop"></div>
            <span class="txt" slot="reference"
              @click="showAgreementTxt">{{queryForm.agreementCategory==1?'查看招投标协议':'查看续签协议'}}</span>
          </el-popover>
        </div>
        <div class="formBox">
          <el-form-item label="签约截止时间" prop="signDeadlineTm">
            <el-date-picker v-model="queryForm.signDeadlineTm" type="datetime" clearable>
            </el-date-picker>
          </el-form-item>
        </div>

        <div class="formBox">
          <el-form-item label="是否交保证金" prop="depositFlag">
            <el-radio-group v-model="queryForm.depositFlag">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item prop="depositRuleId" v-if="queryForm.depositFlag == true">
            <el-select v-model="queryForm.depositRuleId" clearable @focus="handleDepoistRuleClick"
              @change="handleDepoistRuleChange" :loading="depoistRuleLoading">
              <el-option v-for="option in depoistRuleOptions" :key="option.id" :label="option.name" :value="option.id">
              </el-option>
            </el-select>
          </el-form-item>
        </div>

      </el-form>
    </div>
    <div class="messageBox" :style="{ minHeight: height + 'px' }">
      <div class="lineBox commonBox" :style="{ minHeight: height+ 'px' }">
        <div class="clearfix">
          <div style="float: left">线路信息</div>
          <div style="float: right" v-show="ruleForm.lineData.length > 0">
            <el-button type="primary" plain @click="deleteLine">删除</el-button>
            <el-button type="primary" @click="openLineNew">新增</el-button>
          </div>
        </div>
        <div class="listBox" v-show="ruleForm.lineData.length > 0">
          <el-form :model="ruleForm" ref="offerForm">
            <el-table ref="multipleTable" :data="ruleForm.lineData" tooltip-effect="dark" style="width: 100%"
              height="400" @selection-change="handleSelectionLine" :span-method="objectSpanMethod">
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column prop="presellId" label="线路ID">
                <template slot-scope="scope">
                  <span @click="openLineDetail(scope.row.id)" class="clickSpan">{{scope.row.presellId}}</span>
                </template>
              </el-table-column>
              <el-table-column label="车包号" prop="packCode">
              </el-table-column>
              <el-table-column prop="lineCode" label="线路编码" width="150">
              </el-table-column>
              <el-table-column prop="lineId" label="车次ID"> </el-table-column>
              <el-table-column label="始发/目的地城市">
                <template slot-scope="scope">{{ scope.row.originTownName }}/{{
                  scope.row.destinationTownName
                }}</template>
              </el-table-column>
              <el-table-column label="车型/车长（m）">
                <template slot-scope="scope">{{ scope.row.vehicleTypeName }}/{{
                  scope.row.vehicleLength
                }}</template>
              </el-table-column>
              <el-table-column label="计划靠/发/到车时间" width="200">
                <template slot-scope="scope">{{ scope.row.planBerthTime }}/{{ scope.row.planSendTime }}/{{
                  scope.row.planArriveTime
                }}</template>
              </el-table-column>
              <el-table-column prop="workday" label="发车频率">
              </el-table-column>
              <!-- <el-table-column label="是否挂甩">
              <template slot-scope="scope">{{
                scope.row.dumpingTrailers == 1 ? "是" : "否"
              }}</template>
            </el-table-column> -->
              <el-table-column prop="totalKm" label="计划里程（KM）">
              </el-table-column>
              <el-table-column label="线路有效期" width="200">
                <template slot-scope="scope">{{ scope.row.startDate }}/{{ scope.row.endDate }}</template>
              </el-table-column>
              <el-table-column label="线路模式">
                <template
                  slot-scope="scope">{{ scope.row.linePattern?scope.row.linePattern==1?"实际":"预售":"" }}</template>
              </el-table-column>
              <el-table-column label="价格（元/趟）" width="220">
                <template slot-scope="scope">
                  <el-form-item :prop="'lineData.'+scope.$index+'.billPrice'" :rules="rules.billPrice">
                    <el-input-number clearable v-model="scope.row.billPrice" :precision="2" :max="999999999" :min="0">
                    </el-input-number>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
        <div class="noData" v-show="ruleForm.lineData.length == 0">
          <img src="../../../../static/img/noData.png" alt="" />
          <div style="font-size: 14px">
            线路信息为空，<el-link type="primary" @click="openLineNew">去选择线路</el-link>
          </div>
        </div>
      </div>
      <!-- <div style="text-align:right" v-show="lineData.length > 0 && carData.length > 0"> 源代码-->
      <div style="text-align:right" v-show="ruleForm.lineData.length > 0">
        <el-button type="primary" plain @click="quit">取消</el-button>
        <el-button type="primary" @click="createAgreement()" :loading="createLoading">创建协议</el-button>
      </div>
    </div>
    <line-new :show.sync="dialoglineVisible" @getlist="getLinelist"></line-new>
    <line-detail :showLineDetail.sync="showLineDetail" :lineDetailId.sync="lineDetailId" :lineType=1></line-detail>

  </div>
</template>

<script>
  import lineNew from "./lineNew.vue";
  import lineDetail from './lineDetail.vue'
  export default {
    data() {
      var checkPrice = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请填写价格'));
        }
        if (value < 0) {
          callback(new Error('价格必须大于0'));
        } else {
          callback();
        }
      };
      return {
        lineDetailId: '', //查线路详情id
        msg: "111",
        queryForm: {
          agreementType: "2",
          companyName: "",
          supplierUserName: "",
          dateValue: [],
          priceType: "2",
          supplierType: "B",
          driverPhone: "",
          agreementCategory: 2,
          depositFlag: 0,
          depositRuleId: '',
          depositRuleName: '',
          depositRuleCode: '',
          depositRuleVersion: '',
          userScopeValue: '',
        },
        currentUserPage: 1,
        totalUser: 0,
        loading: false,
        loading1: false,
        loading2: false,
        options: [],
        options1: [],
        options2: [],
        companyItem: {},
        supplierItem: {},
        driverItem: {},
        supplierId: "",
        height: 0,
        dialoglineVisible: false,
        dialogcarVisible: false,
        showLineDetail: false, //线路详情弹窗
        lineData: [],
        lineSelection: [],
        carSelection: [],
        ruleForm: {
          lineData: []
        },
        rules: {
          billPrice: [{
              validator: checkPrice,
              trigger: 'blur'
            }
            //{ required: true, message: "请填价格", trigger: "blur" },
            // { min: 0, max: 99999.99, message: '报价区间在0-99999.99', trigger: 'blur' }
          ]
        },
        typeNameList: [],
        agreementTxt: '', //协议文案
        depoistRuleOptions: [], //保证金规则下拉数据对象
        depoistRuleLoading: false, //保证金数据加载状态
        createLoading:false,//提交加载状态
      };
    },
    mounted() {
      this.queryAgreementTypeName() //查协议类别
      this.queryCoConstructionCompanyConfig()
      this.$nextTick(function () {
        var allHeight = $(document).height();
        var offsetHeight = $("#agreementNew").offset().top;
        var h1 = $("#queryNewBox").outerHeight();
        var mainHeight = allHeight - offsetHeight - h1 - 40;
        this.height = mainHeight;
      });
    },
    filters: {
      colorFilter(val) {
        var obj = {
          1: '蓝色',
          2: '黄色',
          3: '绿色'
        }
        if (val) {
          return obj[val]
        } else {
          return ''
        }
      },
      natrueFilter(val) {
        var obj = {
          1: '牵引头',
          2: '半挂车',
          3: '整车',
          4: '牵引货车主车（中置轴）',
          5: '牵引货车挂车（中置轴）'
        }
        if (val) {
          return obj[val]
        } else {
          return ''
        }
      },
      attributeFilter(val) {
        var obj = {
          1: '金融车',
          2: '自有车',
          3: '普通B端车'
        }
        if (val) {
          return obj[val]
        } else {
          return ''
        }
      }
    },
    methods: {
    //通过列表数据生成一个与行数相同的数组记录每一行设置的合并数
    getOrderNumber(data) {
      this.spanArr = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].combinationNumber === data[i - 1].combinationNumber && data[i].lineSource == 2 && data[i].lineSource == data[i - 1].lineSource) {
              this.spanArr[this.pos] += 1;
              this.spanArr.push(0);
            } else {
              this.spanArr.push(1);
              this.pos = i;
            }
        }
      }
    },
    //合并行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (
        columnIndex === 0 ||
        columnIndex === 2 
      ) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
      openLineDetail(val) {
        this.lineDetailId = val
        this.showLineDetail = true
      },
      /* 查看协议文案 */
      showAgreementTxt() {
        this.agreementTxt = ''
        if (!this.queryForm.agreementCategory) {
          this.$message({
            message: '请先选择协议类别',
            type: "warning"
          });
          return
        }

        let param = {
          typeCode: this.queryForm.agreementCategory,
          clientType: this.queryForm.supplierType
        }
        this.$httpExt().post("trade/AgreementTextManage/queryAgreementTextWeb", param)
          .then((response) => {
            if (response.result && response.succ == 'ok') {
              this.agreementTxt = response.result.htmlContent
            }
          }, (response) => {});
      },
      afterLeave() {
        this.currentUserPage = 1;
        if (JSON.stringify(this.driverItem) == "{}") {
          this.queryForm.driverPhone = "";
        }
      },
      chooseUserName(data) {
        // this.formInline.userName = data.driverName + '/' + data.userPhone
        // this.formInline.userId = data.userId
        // this.formInline.phone = data.userPhone
        // this.formInline.carCode =""
        this.queryForm.driverPhone = data.blName + '/' + data.moreContactorPhone
        this.driverItem = data;
        this.totaUser = 0
        this.currentUserPage = 1
        //this.nameChange(data.userId)
        this.$refs.deptPop.doClose()
      },
      /* 查协议类型 */
      queryAgreementTypeName() {
        this.$httpExt().post("trade/AgreementTextManage/queryAgreementTypeName", {})
          .then((response) => {
            if (response.result && response.succ == 'ok') {
              this.typeNameList = response.result.filter(item => item.typeCode!=1)

            }
          }, (response) => {});
      },
      userPageChange(val) {
        this.currentUserPage = val
        this.queryUserInfoByPage()
      },
      queryUserInfoByPage() {
        this.driverItem = {};
        this.options2 = [];
        //校验输入框是否为数字
        const num = /^[0-9]*$/;
        var query = this.queryForm.driverPhone;
        var param = {};
        if (num.test(query)) {
          if ((query && query.length <= 10)) {
            this.totalUser = 0
            this.currentUserPage = 1
            return
          }
          param = {
            'userName': "",
            "driverPhone": query,
            'userId': "",
            page: this.currentUserPage,
            pageSize: 5
          }
        } else {
          param = {
            'userName': query,
            "driverPhone": "",
            'userId': "",
            page: this.currentUserPage,
            pageSize: 5
          }
        }
        this.loading2 = true;
        this.$httpExt().post("/trade/biddingAgreementManage/addAgreementQueryDriverInfo", param).then(response => {
          this.loading2 = false;
          if (response.succ == "ok") {
            var list = response.result.userList;
            if (list && list.length > 0) {
              this.options2 = list;
            }
            this.totalUser = response.result.total
          } else {
            this.options2 = [];
            this.totalUser = 0;
            this.$message({
              message: response.result.errorMessage,
              type: "warning"
            });
          }
        }, response => {
          this.options2 = [];
          this.totalUser = 0;
          this.$message({
            message: response.msg,
            type: 'warning'
          })
        })
      },
      quit() {
        this.$confirm("确定放弃创建协议？取消后，已填写的协议内容将不再保留", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$refs.agreementForm.resetFields();
          this.ruleForm.lineData = [];
          this.supplierItem = {};
          this.companyItem = {};
          this.driverItem = {};
        }).catch(() => {

        });
      },
      createCheckSaasTime() {
        this.$confirm("标的与saas招投标协议有冲突，请确认时间是否能衔接上，避免误操作。确认无误请继续。", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.createAgreement(1, null); //要跳过校验 传1 不做校验
        }).catch(() => {

        });
      },
      createCheckBiddingTime() {
        this.$confirm("标的与竞价协议有冲突，请确认时间是否能衔接上，避免误操作。确认无误请继续。", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.createAgreement(1, 1); //要跳过校验 传1 不做校验
        }).catch(() => {

        });
      },
      createAgreement(checkTimeFlag, checkBiddingTimeFlag) { //创建
        if (!this.queryForm.agreementType) {
          this.$message({
            message: '请选择协议类型',
            type: "warning"
          });
          return
        }
        if (!this.queryForm.companyName) {
          this.$message({
            message: '请选择公司名称',
            type: "warning"
          });
          return
        }
        if (this.queryForm.supplierType == "B") {
          if (!this.queryForm.supplierUserName) {
            this.$message({
              message: '请选择承运商',
              type: "warning"
            });
            return
          }
        } else {
          if (!this.queryForm.driverPhone) {
            this.$message({
              message: '请选择司机手机号',
              type: "warning"
            });
            return
          }
        }

        if (this.queryForm.dateValue.length == 0) {
          this.$message({
            message: '请选择协议生/失效日期',
            type: "warning"
          });
          return
        }
        // }else{
        //     var time1 = this.queryForm.dateValue[0].getTime();
        //     var time2 = new Date().getTime();
        //     if(time1<time2){
        //       this.$message({ message: '协议生效时间只能大于等于当前时间，不能小于', type: "warning" });
        //       return
        //     }
        // }
        if (!this.queryForm.signDeadlineTm) {
          this.$message({
            message: '请选择签约截止时间',
            type: "warning"
          });
          return
        } else {
          let signTm = Date.parse(this.queryForm.signDeadlineTm)
          if (signTm < new Date()) {
            this.$message({
              message: '签约截止时间需大于当前时间',
              type: "warning"
            });
            return
          }
        }

        if (!this.queryForm.priceType) {
          this.$message({
            message: '请选择计价方式',
            type: "warning"
          });
          return
        }
        if (this.ruleForm.lineData.length > 50) {
          this.$message({
            message: '新增选择线路-最多50条',
            type: "warning"
          });
          return
        }

        if (this.queryForm.depositFlag && !this.queryForm.depositRuleId) {
          this.$message({
            message: '请选择保证金规则',
            type: "warning"
          });
          return
        }

        this.$refs['offerForm'].validate((valid) => {
          if (valid) {
            var tempItem = {}
            if (this.queryForm.supplierType == "B") {
              tempItem = this.supplierItem
            } else {
              tempItem = this.driverItem
            }
            var params = {
              agreementType: this.queryForm.agreementType,
              companyName: this.queryForm.companyName, //公司名称
              companyId: this.companyItem.id, //公司id
              companyUserName: this.companyItem.username, //公司 主账号 名称
              companyUserId: this.companyItem.userId, //公司 主账号 userId
              companyOwnerUscCode: this.companyItem.blRegisterNumber, //公司统一信用代码
              companyContactUser: this.companyItem.moreBusinessContactor, //公司联系人
              companyContactPhone: this.companyItem.moreContactorPhone, //公司联系电话
              carrierType: this.queryForm.supplierType,
              supplierUserId: tempItem.userId,
              supplierId: tempItem.id,
              supplierUserName: this.queryForm.supplierType == "B" ? this.queryForm.supplierUserName : tempItem
                .userName,
              supplierName: tempItem.blName,
              lineEffectTm: this.queryForm.dateValue[0],
              lineExpireTm: this.queryForm.dateValue[1],
              ownerUscCode: tempItem.blRegisterNumber,
              contactUser: tempItem.moreBusinessContactor,
              contactPhone: tempItem.moreContactorPhone,
              priceType: this.queryForm.priceType,
              lineList: this.ruleForm.lineData,
              signDeadlineTm: this.queryForm.signDeadlineTm,
              agreementCategory: this.queryForm.agreementCategory,
              checkTimeFlag: checkTimeFlag,
              checkBiddingTimeFlag: checkBiddingTimeFlag,
              depositFlag: this.queryForm.depositFlag,

            }

            if (this.queryForm.depositFlag == 1) {
              params.depositRuleId = this.queryForm.depositRuleId;
              params.depositRuleCode = this.queryForm.depositRuleCode;
              params.depositRuleName = this.queryForm.depositRuleName;
              params.depositRuleVersion = this.queryForm.depositRuleVersion;
              params.userScopeValue = this.queryForm.userScopeValue;
            }
            this.createLoading = true;
            this.$httpExt()
              .post("/trade/biddingAgreementManage/addBidAgreement", params)
              .then(
                (response) => {
                  this.createLoading = false;
                  if (response.succ == "ok") {
                    this.$message({
                      message: "新增成功",
                      type: "success"
                    });
                    this.$emit(
                      "page",
                      "招投标协议管理",
                      function (resolve) {
                        require(["./biddingAgreementManage.vue"], resolve);
                      },
                      "1041504"
                    );
                    this.$emit("removePage", "新建招投标协议")

                  } else {
                    this.$message({
                      message: response.msg,
                      type: "warning"
                    });
                  }
                },
                (response) => {
                  this.createLoading = false;
                  if (response.result.errorCode != 23 && response.result.errorCode != 24) { //招投标时间冲突不需要错误提示，其他需要提示
                    this.$message({
                      message: response.msg,
                      type: "warning"
                    });
                  }

                  //注：校验顺序不能改，会死循环
                  if (response.result.errorCode == 23) { //是否需要校验招投标协议时间冲突
                    this.createCheckSaasTime();
                  }
                  //注：校验顺序不能改，会死循环
                  if (response.result.errorCode == 24) { //是否需要校验竞价
                    this.createCheckBiddingTime();
                  }

                }
              );
          } else {
            this.$message({
              message: "请填写价格",
              type: "warning"
            });
            return false;
          }
        });



      },
      queryCoConstructionCompanyConfig() {
        this.$httpExt()
          .post("trade/coConstructionAgreement/queryCoConstructionCompanyConfig", {})
          .then(
            (response) => {
              if (response.succ == "ok" && response.result) {
                var result = response.result;
                if (result.success) {
                  this.options = result.obj;
                } else {
                  this.$message({
                    message: result.errorMessage,
                    type: "warning"
                  });
                }
              } else {
                this.$message({
                  message: response.msg,
                  type: "warning"
                });
              }
            },
            (response) => {
              this.$message({
                message: response.msg,
                type: "warning"
              });
            }
          );
      },
      selectCompany() {
        if (this.queryForm.companyName) {
          this.$httpExt()
            .post("trade/coConstructionAgreement/querySupplierByBlName", {
              blName: this.queryForm.companyName
            })
            .then(
              (response) => {
                if (response.succ == "ok" && response.result) {
                  var result = response.result;
                  console.log(result);
                  if (result.success) {
                    this.companyItem = result.obj;
                  } else {
                    this.companyItem = {};
                    this.$message({
                      message: result.errorMessage,
                      type: "warning"
                    });
                  }
                } else {
                  this.$message({
                    message: response.msg,
                    type: "warning"
                  });
                }
              },
              (response) => {
                this.$message({
                  message: response.msg,
                  type: "warning"
                });
              }
            );
        }

      },
      remoteSupplier(query) {
        if (query !== "") {
          this.loading1 = true;
          this.$httpExt()
            .post("trade/coConstructionAgreement/searchListInfoByBlName", {
              blName: query,
            })
            .then(
              (response) => {
                this.loading1 = false;
                if (response.succ == "ok" && response.result) {
                  var result = response.result;
                  if (result.success) {
                    this.options1 = result.obj;
                  } else {
                    this.options1 = [];
                    this.$message({
                      message: result.errorMessage,
                      type: "warning"
                    });
                  }
                } else {
                  this.$message({
                    message: response.msg,
                    type: "warning"
                  });
                }
              },
              (response) => {
                this.$message({
                  message: response.msg,
                  type: "warning"
                });
              }
            );
        } else {
          this.options = [];
        }
      },
      remoteDriver(query) {
        if (query !== "") {
          this.loading2 = true;
          this.$httpExt()
            .post("trade/coConstructionAgreement/queryByMobilePhone", {
              mobilePhoneList: query,
            })
            .then(
              (response) => {
                this.loading2 = false;
                if (response.succ == "ok" && response.result) {
                  var result = response.result;
                  if (result.success) {
                    this.options2 = result.obj;
                  } else {
                    this.options2 = [];
                    this.$message({
                      message: result.errorMessage,
                      type: "warning"
                    });
                  }
                } else {
                  this.$message({
                    message: response.msg,
                    type: "warning"
                  });
                }
              },
              (response) => {
                this.$message({
                  message: response.msg,
                  type: "warning"
                });
              }
            );
        } else {
          this.options2 = [];
        }
      },
      selectSupplier(val) {
        this.options1.forEach(item => {
          if (item.username == val) {
            this.supplierItem = item;
          }
        });
      },
      selectDriver(val) {

      },
      openLineNew() {
        if (!this.queryForm.agreementType) {
          this.$message({
            message: '请选择协议类型',
            type: "warning"
          });
          return
        }
        this.dialoglineVisible = true;
      },
      openCarNew() {
        if (!this.queryForm.supplierUserName) {
          this.$message({
            message: '请先选择承运商',
            type: "warning"
          });
          return
        }
        this.dialogcarVisible = true;
      },
      deleteCommon(data, selection, flag) {
        var type
        if (flag == 1) {
          type = "线路"
        } else if (flag == 2) {
          type = "车辆"
        }
        this.$confirm(`确定删除选中的${selection.length}条${type}信息`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var length2 =data.length
            for(var i = 0;i<selection.length;i++){
              for(var j =0;j<length2;j++){
                  if(data.length > 0){
                      if(selection[i].combinationNumber == data[j].combinationNumber){
                            data.splice(j,data.length)
                            // length2--;
                            this.queryForm.dateValue = [];//删除线路，清空生失效时间
                      }
                  }
              }
            }
          let list = data.filter(item => {
            if (!selection.includes(item)) {
              return item
            }
          })
          if (flag == 1) {
            this.ruleForm.lineData = list;
          }
        }).catch(() => {

        });
      },
      deleteLine() {
        this.deleteCommon(this.ruleForm.lineData, this.lineSelection, 1)
      },
      getLinelist(val) {
        //  var length1 = this.ruleForm.lineData.length;
        // var length2 = val.length;
        //  for(var i = 0 ;i<length1;i++){
        //     for(var j = 0;j<length2;j++){
        //        if(this.ruleForm.lineData.length>0){
        //           if(val[j].id == this.ruleForm.lineData[i].id){
        //               this.ruleForm.lineData.splice(i,1)
        //               length1--;
        //           }
        //        }

        //     }
        //  }
        //  this.ruleForm.lineData = [...this.ruleForm.lineData,...val];
        // this.ruleForm.lineData = val;
        //调接口查询数据
        this.queryUncheckedLineListByCombinationNumber(val[0]);
      },
      queryUncheckedLineListByCombinationNumber(val){
        let params = {
          combinationNumber: val.combinationNumber,
          lineSource: val.lineSource,
          requireLabelEnum: 2
        }
        this.$httpExt()
          .post("trade/lineManagement/queryUncheckedLineListByCombinationNumber", params)
          .then(
            (response) => {
              if (response.succ == "ok" && response.result) {
                var result = response.result;
                if(result.lineList){
                  this.ruleForm.lineData = result.lineList;
                }
                if(result.onlineDate && result.offlineDate){
                  this.queryForm.dateValue = [result.onlineDate,result.offlineDate];
                } else {
                  this.queryForm.dateValue = [];
                }
                this.getOrderNumber(this.ruleForm.lineData);
              } else {
                this.$message({ message: response.msg, type: "warning" });
              }
            },
            (response) => {
              this.$message({ message: response.msg, type: "warning" });
            }
        );
    },
      handleSelectionLine(val) {
        this.lineSelection = val;
      },
      clearCompany() {
        this.companyItem = {};
      },
      clearSupplier() {
        this.supplierItem = {};
      },
      clearDriver() {
        this.driverItem = {};
      },
      agreementTypeChange(val) {
        if (val == 2) {
          this.queryForm.priceType = "2";
        } else {
          this.queryForm.priceType = "";
        }
      },
      priceTypeChange(val) {
        if (val == 6) {
          this.queryForm.agreementType = "1";
        } else if (val == 2) {
          this.queryForm.agreementType = "2";
        } else {
          this.queryForm.agreementType = "";
        }
        this.ruleForm.lineData = [];
        this.lineSelection = [];
      },
      handleDepoistRuleClick() {
        this.depoistRuleLoading = true;
        this.$httpExt().post('saasDepoist/depositRule/select', {
          page: 1,
          pageSize: 1000,
          tenantId: 'TBP',
          scene: 2,
          payModePerson: 3,
          payModeCompany: 3,
          status: 1
        }).then((response) => {
          this.depoistRuleLoading = false;

          if (response.succ == 'ok') {
            this.depoistRuleOptions = response.result.list;
            this.$nextTick(() => {
              if (response.result.list && response.result.list.length > 0) {
                this.queryForm.depositRuleId = response.result.list[0].id;
                this.queryForm.depositRuleName = response.result.list[0].name;
                this.queryForm.depositRuleCode = response.result.list[0].ruleCode;
                this.queryForm.depositRuleVersion = response.result.list[0].version;
                this.queryForm.userScopeValue = response.result.list[0].userScopeValue;
              }
            });
          }
        }, (response) => {
          this.depoistRuleLoading = false;
        });
      },
      handleDepoistRuleChange(id) {
        const option = this.depoistRuleOptions.find((item) => {
          return item.id == id;
        })
        if (option) {
          this.queryForm.depositRuleName = option.name;
          this.queryForm.depositRuleCode = option.ruleCode;
          this.queryForm.depositRuleVersion = option.version;
          this.queryForm.userScopeValue = option.userScopeValue;
        }
      }
    },
    components: {
      lineNew,
      lineDetail
    },
  };

</script>

<style lang="less" scoped>
  @commonYellow: #ff6d00;

  .agreementNew {
    background: #f5f5f5;
    margin: -10px -15px;
    padding-top: 1px;
    box-sizing: border-box;
  }

  .select-wrap {
    padding: 20px;
    margin: 0 8px;
    background: white;
    margin: 8px 0;
  }

  .formTips {
    margin-left: 25px;
    line-height: 35px;
    font-size: 14px;
  }

  .formBox {
    margin-bottom: 10px;
  }

  .messageBox {
    background: #fff;
    padding: 15px 25px;
    box-sizing: border-box;

    .commonBox {
      position: relative;

      .noData {
        text-align: center;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }

    .listBox {
      margin: 10px 0;
      padding: 10px 0;
    }
  }

  /deep/ .el-button--primary.is-plain {
    color: @commonYellow;
    background: #ffffff;
    border-color: @commonYellow;
  }

  /deep/ .el-button--primary.is-plain:hover {
    background: @commonYellow;
    border-color: commonYellow;
    color: #fff;
  }

  /deep/ .el-button--primary {
    color: #fff;
    background-color: @commonYellow;
    border-color: @commonYellow;
  }

  /deep/ .listBox .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: @commonYellow;
    border-color: @commonYellow;
  }

  /deep/ .listBox .el-checkbox__input.is-indeterminate .el-checkbox__inner {
    background-color: @commonYellow;
    border-color: @commonYellow;
  }

  /deep/ .listBox .el-form-item {
    margin-bottom: 20px !important;
  }

  /deep/ .listBox .el-form-item .el-form-item__content .el-input .el-input__inner {
    height: auto !important;
    line-height: 40px !important;
  }

  .clearfix:after {
    content: "";
    height: 0;
    line-height: 0;
    display: block;
    visibility: hidden;
    clear: both;
  }

  .clearfix:after {
    *zoom: 1;
    /*针对IE6/IE7*/
  }

  .userItem {
    cursor: pointer;
    padding: 5px 0;
  }

  .userItem:hover {
    background: #ff6d00;
    color: #fff;
  }

  .txt {
    margin-top: 5px;
    color: #409EFF;
    cursor: pointer;
    display: inline-block;
  }

  #agreementPop {
    max-height: 400px;
    overflow: scroll;
  }

  .clickSpan {
    color: #409EFF;
    cursor: pointer;
  }
 .dateBox /deep/ .el-form-item .el-form-item__content {
   width: 650px; 
}
</style>
